<template>
	<view class="content">
		<image class="logo" src="/static/logo.png"></image>
		<view class="text-area">
			<text class="title">{{title}}</text>
		</view>
		<u-calendar :show="show" @close="close"></u-calendar>
		<u-button @click="show = true">打开</u-button>
		<u-button @click="toLogin">login</u-button>
		
		<view class="section">
		      <text class="section-title">1. 密钥管理</text>
		      <button @click="generateKeys" :disabled="loading" class="btn">
		        {{ loading ? '生成中...' : '生成密钥对' }}
		      </button>
		      
		      <view v-if="keys.publicKey" class="key-info">
		        <text class="key-label">公钥:</text>
		        <text class="key-text">{{ keys.publicKey.substring(0, 50) }}...</text>
		        <text class="key-label">私钥:</text>
		        <text class="key-text">{{ keys.privateKey.substring(0, 50) }}...</text>
		      </view>
		    </view>
		
		    <view class="section">
		      <text class="section-title">2. 数据加密</text>
		      <textarea 
		        v-model="inputData" 
		        placeholder="请输入要加密的数据"
		        class="input-area"
		      />
		      <button @click="encryptData" :disabled="!keys.publicKey || loading" class="btn">
		        加密数据
		      </button>
		      
		      <view v-if="encryptedResult" class="result">
		        <text class="result-label">加密结果:</text>
		        <text class="result-text">{{ encryptedResult.substring(0, 100) }}...</text>
		      </view>
		    </view>
		
		    <view class="section">
		      <text class="section-title">3. 数据解密</text>
		      <button @click="decryptData" :disabled="!encryptedResult || loading" class="btn">
		        解密数据
		      </button>
		      
		      <view v-if="decryptedResult" class="result">
		        <text class="result-label">解密结果:</text>
		        <text class="result-text">{{ decryptedResult }}</text>
		      </view>
		    </view>
		
		    <view class="section">
		      <text class="section-title">4. 验证结果</text>
		      <view v-if="decryptedResult" class="verification">
		        <text class="verification-text">
		          {{ isVerified ? '✓ 加密解密成功！' : '✗ 加密解密失败！' }}
		        </text>
		      </view>
		    </view>
		
		    <view class="section">
		      <text class="section-title">5. 测试功能</text>
		      <button @click="testChinese" :disabled="loading" class="btn">
		        测试中文加密
		      </button>
		      <button @click="testLargeData" :disabled="loading" class="btn">
		        测试大数据加密
		      </button>
		      <button @click="clearAll" class="btn btn-clear">
		        清除所有数据
		      </button>
		    </view>
	</view>
</template>

<script>
	import RSASegmentCrypto from '@/utils/crypto.js'

	export default {
		data() {
			return {
				title: 'Hello',
				show: false,
				rsaCrypto: null,
			  keys: {
				publicKey: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqYDnNgGpi8s5FR3d9ASco08WZFd5HNE+oAYFgr5nFRNPScV0DqXLU9oM+eeW0cyRmnh+WfrCUL2cUopwns4wv0O9lM93Ljaiskfjrwrrred7G82AAt6UfQNmheOcrQrKLU8znzDQ3N8cO6cD1CbuWgKB2JlndxotJFhO5OK4avwIDAQAB',
				privateKey: 'MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKpgOc2AamLyzkVHd30BJyjTxZkV3kc0T6gBgWCvmcVE09JxXQOpctT2gz555bRzJGaeH5Z+sJQvZxSinCezjC/Q72Uz3cuNqKyR+OvCuut53sbzYAC3pR9A2aF45ytCsotTzOfMNDc3xw7pwPUJu5aAoHYmWd3Gi0kWE7k4rhq/AgMBAAECgYAWEijFcYfBRraoQeBS7hXOaP9VhqreAC2mKX/C8IHpN10rYKp4gXh8lGyfE3fJfwsC93lHFnq1z52OY5xQBlHitCIbVfsFg0oi3AV6IzM8/rWc44XYiIUkABlhf/tEMeflzMjnNCfJ0pLiJVyiz6nE4IOM90jWORiZSozvTzjleQJBAK0soTbh2thC986hszj5xoWQ2kZzW9rL6keCNw3PBZ2pCutuSi8g81htE7jenP43gptZDg++HutQ2TFpXzb/5ucCQQD73PR7mU7Dgn+Xn2yVRZvXiNT0m5bQqoiMPm91Sc4NkTPBqJ5Gcusb7yPV9lNaImDjvkc17dBMGqDZKj9tJappAkATOTAQMpQji5OMmYCWo4t5CjJgva+Fozs3gunvm3qJHNm8drq/bo300+7rh7KvuaPC8OjRsI4oGwpxJLxQE6ojAkEAtXJTN5AU7Ejhfuw9n7SMN1S+hpJorl+NC+wXBBpttdx7uvKtQ/eaZX99A7H4DqFhx/DXAIUZYRp18r26//j4sQJACSoqJWa8cNhmF7+TPK6OmKmLzdQ+X91AWosT5YIld2N4Ri7yVlzo8/9rRtP82b7Xk5OdlxVPNIAEXWEeAs7nag=='
			  },
			  inputData: '',
			  encryptedResult: '',
			  decryptedResult: '',
			  loading: false
			}
		},
		computed: {
		    isVerified() {
		      return this.inputData && this.decryptedResult && 
		             this.inputData === this.decryptedResult;
		    }
		  },
		onLoad() {
			this.rsaCrypto = new RSASegmentCrypto(1024);
			this.loadKeysFromStorage();
			const token = uni.getStorageSync("token")
			if (token === undefined || token === '') {
				uni.redirectTo({
					url: "/pages/login/login"
				})
			}
		},
		methods: {
				
			close() {
				this.show = false
			},
			toLogin() {
				uni.redirectTo({
					url: "/pages/login/login"
				})
			},
			async generateKeys() {
			      this.loading = true;
			      try {
			        this.keys = await this.rsaCrypto.generateKeyPair();
			        this.saveKeysToStorage();
			        uni.showToast({
			          title: '密钥生成成功',
			          icon: 'success'
			        });
			      } catch (error) {
			        uni.showToast({
			          title: '密钥生成失败',
			          icon: 'error'
			        });
			        console.error('密钥生成失败:', error);
			      } finally {
			        this.loading = false;
			      }
			    },
			
			    async encryptData() {
			      if (!this.inputData.trim()) {
			        uni.showToast({
			          title: '请输入要加密的数据',
			          icon: 'none'
			        });
			        return;
			      }
			
			      this.loading = true;
			      try {
			        this.encryptedResult = this.rsaCrypto.signWithPrivateKey(
			          this.inputData, 
			          this.keys.privateKey
			        );
					console.log(this.encryptedResult)
			        uni.showToast({
			          title: '加密成功',
			          icon: 'success'
			        });
			      } catch (error) {
			        uni.showToast({
			          title: '加密失败',
			          icon: 'error'
			        });
			        console.error('加密失败:', error);
			      } finally {
			        this.loading = false;
			      }
			    },
			
			    async decryptData() {
			      this.loading = true;
			      try {
			        this.decryptedResult = this.rsaCrypto.verifyWithPublicKey(
			          this.encryptedResult, 
			          this.keys.publicKey
			        );
					console.log(this.decryptedResult)
			        uni.showToast({
			          title: '解密成功',
			          icon: 'success'
			        });
			      } catch (error) {
			        uni.showToast({
			          title: '解密失败',
			          icon: 'error'
			        });
			        console.error('解密失败:', error);
			      } finally {
			        this.loading = false;
			      }
			    },
			
			    async testChinese() {
			      this.inputData = '你好，世界！这是一个中文测试消息。' + 
			                      'RSA加密算法可以很好地处理中文字符。' +
			                      '这个消息比较长，需要分段处理。';
			      uni.showToast({
			        title: '已设置中文测试数据',
			        icon: 'success'
			      });
			    },
			
			    async testLargeData() {
			      // 生成大数据进行测试
			      const largeData = 'A'.repeat(200) + 'B'.repeat(200) + 'C'.repeat(200);
			      this.inputData = largeData;
			      uni.showToast({
			        title: '已设置大数据测试',
			        icon: 'success'
			      });
			    },
			
			    saveKeysToStorage() {
			      try {
			        this.rsaCrypto.saveKeyToStorage(this.keys.publicKey, 'rsa_public_key');
			        this.rsaCrypto.saveKeyToStorage(this.keys.privateKey, 'rsa_private_key');
			      } catch (error) {
			        console.error('保存密钥失败:', error);
			      }
			    },
			
			    loadKeysFromStorage() {
			      try {
			        const publicKey = this.rsaCrypto.loadKeyFromStorage('rsa_public_key');
			        const privateKey = this.rsaCrypto.loadKeyFromStorage('rsa_private_key');
			        
			        if (publicKey && privateKey) {
			          this.keys = { publicKey, privateKey };
			        }
			      } catch (error) {
			        console.error('加载密钥失败:', error);
			      }
			    },
			
			    clearAll() {
			      this.inputData = '';
			      this.encryptedResult = '';
			      this.decryptedResult = '';
			      this.keys = { publicKey: '', privateKey: '' };
			      
			      // 清除存储的密钥
			      try {
			        uni.removeStorageSync('rsa_public_key');
			        uni.removeStorageSync('rsa_private_key');
			      } catch (error) {
			        console.error('清除存储失败:', error);
			      }
			      
			      uni.showToast({
			        title: '数据已清除',
			        icon: 'success'
			      });
			    }
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
	
	.container {
	  padding: 20rpx;
	  background-color: #f5f5f5;
	  min-height: 100vh;
	}
	
	.header {
	  text-align: center;
	  margin-bottom: 40rpx;
	}
	
	.title {
	  font-size: 36rpx;
	  font-weight: bold;
	  color: #333;
	}
	
	.section {
	  background-color: #fff;
	  border-radius: 16rpx;
	  padding: 30rpx;
	  margin-bottom: 30rpx;
	  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}
	
	.section-title {
	  font-size: 32rpx;
	  font-weight: bold;
	  color: #333;
	  margin-bottom: 20rpx;
	  display: block;
	}
	
	.btn {
	  background-color: #007aff;
	  color: #fff;
	  border: none;
	  border-radius: 8rpx;
	  padding: 20rpx 40rpx;
	  margin: 10rpx 0;
	  font-size: 28rpx;
	}
	
	.btn:disabled {
	  background-color: #ccc;
	}
	
	.btn-clear {
	  background-color: #ff3b30;
	}
	
	.key-info {
	  margin-top: 20rpx;
	  padding: 20rpx;
	  background-color: #f8f9fa;
	  border-radius: 8rpx;
	}
	
	.key-label {
	  font-size: 24rpx;
	  color: #666;
	  display: block;
	  margin-top: 10rpx;
	}
	
	.key-text {
	  font-size: 24rpx;
	  color: #333;
	  word-break: break-all;
	  display: block;
	  margin-bottom: 10rpx;
	}
	
	.input-area {
	  width: 100%;
	  height: 200rpx;
	  border: 2rpx solid #ddd;
	  border-radius: 8rpx;
	  padding: 20rpx;
	  font-size: 28rpx;
	  margin-bottom: 20rpx;
	  box-sizing: border-box;
	}
	
	.result {
	  margin-top: 20rpx;
	  padding: 20rpx;
	  background-color: #f8f9fa;
	  border-radius: 8rpx;
	}
	
	.result-label {
	  font-size: 24rpx;
	  color: #666;
	  display: block;
	  margin-bottom: 10rpx;
	}
	
	.result-text {
	  font-size: 24rpx;
	  color: #333;
	  word-break: break-all;
	  display: block;
	}
	
	.verification {
	  text-align: center;
	  padding: 20rpx;
	}
	
	.verification-text {
	  font-size: 32rpx;
	  font-weight: bold;
	  color: #28a745;
	}
	
	.verification-text:not(.success) {
	  color: #dc3545;
	}
</style>
